package com.ilxqx.framework.util;

import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.io.*;
import java.util.Base64;

/**
 * 对象操作工具类
 * @author venus
 */
@Slf4j
public class ObjectUtils {

    /**
     * 序列化一个对象为字符串
     * @param object 对象
     * @return 序列化后的字符串（Base64）
     */
    @NotNull
    public static String serializeObjectToString(@NotNull Object object) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        try {
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);
            objectOutputStream.writeObject(object);
        } catch (IOException e) {
            log.warn("对象[{}]序列化失败：{}", InfoUtils.stringify(object), e);
            return "";
        }
        return Base64.getEncoder().encodeToString(outputStream.toByteArray());
    }

    /**
     * 反序列化一个字符串为对象
     * @param stringObject 字符串
     * @return 反序列化后的对象，如果可以序列化成功的话
     */
    @Nullable
    public static Object deserializeObjectFromString(@NotNull String stringObject) {
        byte[] bytes = Base64.getDecoder().decode(stringObject);
        ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
        try {
            ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);
            return objectInputStream.readObject();
        } catch (IOException | ClassNotFoundException e) {
            log.warn("字符串对象[{}]反序列化失败：{}", stringObject, e);
            return null;
        }
    }

}
